import logging
import time
from datetime import timedelta, datetime

import baostock as bs
import pymysql

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s | %(filename)s - {%(lineno)d} - [%(levelname)s] - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S', encoding='utf-8')

mysql_host = "127.0.0.1"
mysql_port = 3306

connect = pymysql.connect(host=mysql_host, port=mysql_port, user='root', passwd='hxsoft.net', database='stock')
cursor = connect.cursor()

bs.login()


def get_stock_his_data(stock_code):
    today = datetime.today().strftime('%Y-%m-%d')

    if stock_code[0: 2] == '60' or stock_code[0: 2] == '68':
        sec_id = "sh." + str(stock_code)
    else:
        sec_id = "sz." + str(stock_code)

    cursor.execute(
        "select stock_date from stock.stock_details where stock_code = '%s' order by stock_date desc limit 1" % stock_code)
    result = cursor.fetchone()

    rs = None

    if result is None:
        rs = bs.query_history_k_data_plus(sec_id,
                                          "code,date,open,high,low,close,preclose,volume,amount,turn,pctChg",
                                          start_date="2018-01-01", end_date=today, frequency="d", adjustflag="2")
    else:
        lastDay = result[0]
        next_day = lastDay + timedelta(days=1)
        if next_day.__lt__(datetime.today()):
            lastDay = next_day.strftime('%Y-%m-%d')
            rs = bs.query_history_k_data_plus(sec_id,
                                              "code,date,open,high,low,close,preclose,volume,amount,turn,pctChg",
                                              start_date=lastDay, end_date=today, frequency="d", adjustflag="2")
        else:
            print("current stock: {} has fetched all data!!!".format(stock_code))

    if rs is not None:
        while (rs.error_code == '0') & rs.next():
            stock_data_list = rs.get_row_data()
            code = stock_data_list[0][3:]
            date = stock_data_list[1]
            open = stock_data_list[2]
            high = stock_data_list[3]
            low = stock_data_list[4]
            close = stock_data_list[5]
            preclose = '0' if stock_data_list[6] == '' else stock_data_list[6]
            volume = '0' if stock_data_list[7] == '' else stock_data_list[7]
            amount = '0' if stock_data_list[8] == '' else stock_data_list[8]
            turn = '0' if stock_data_list[9] == '' else stock_data_list[9]
            chg = '0' if stock_data_list[10] == '' else stock_data_list[10]

            sql = "insert into stock.stock_details(stock_code,stock_date,open,close,high,low,vol,amount,pchange,increment,preclose) values ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % (
                code, date, open,
                close, high, low,
                volume, amount, turn,
                chg, preclose)

            print(sql)
            cursor.execute(sql)
            connect.commit()


cursor.execute("select sc.stock_code,sc.stock_name from stock.stock_code sc")
rows = cursor.fetchall()
for row in rows:
    _stock_code = row[0]
    get_stock_his_data(_stock_code)
    logging.info("stock: {} fetch list successful!!!".format(_stock_code))
    time.sleep(0.5)

bs.logout()
